package org.jadedanha.dao;

import java.sql.*;
import java.util.*;
import org.jadedanha.model.*;

public class UsuarioDao extends Dao {

    public Integer lastInsertedId;

    public void save( Usuario usuario ) throws SQLException {
        String sql;

        sql = "INSERT INTO usuario (nome, senha, email) VALUES(?, ?, ?)";

        PreparedStatement stm = this.getConnection().prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);

        stm.setString(1, usuario.getNome() );
        stm.setString(2, usuario.getEmail().toString() );
        stm.setString(3, usuario.getSenha().toString() );

        stm.execute();

        ResultSet keys = stm.getGeneratedKeys();

        if ( keys != null && keys.next() ) {
            this.setUltimo( keys.getInt(1) );
        }

        stm.close();
    }

    public Integer getUltimo() {
        return this.lastInsertedId;
    }

    public void setUltimo( Integer last ) {
        this.lastInsertedId = last;
    }

    public static void main (String[] args) throws SQLException {
/*
        UsuarioDao ud = new UsuarioDao();
        Usuario u = new Usuario()
            .setNome("teste 1")
            .setSenha( new Senha("senha teste") )
            .setEmail( new Email("teste@teste.com") );

        try {
            ud.save( u );
            System.out.println("foi");
        }
        catch ( Exception e ) {
            System.out.println("ai cacete...");
            e.printStackTrace();
        }
*/

        System.out.println("I exist!");
    }
}
